import sys
import os

from http import HTTPStatus

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, ".."))
sys.path.append(os.path.join(thisDir, "..", "ps"))
sys.path.append(os.path.join(thisDir, "..", "..", "common"))

from EJOHandlerBase import EJOHandlerBase
from SessionManager import SessionManager

import EJOConst

import logging
logger = logging.getLogger(__name__)

class EJOLogin(EJOHandlerBase):
    def _doHandle(self):
        logger.debug(f"Handled by: {__name__}")

        username = self._getParamValue("username")
        password = self._getParamValue("password")
        sql = "select " + \
            "authentication.Authentication as authentication, person.FID as family" + \
            " from " + \
            "authentication, person" + \
            " where " + \
            "authentication.PID=person.ID" + \
            " and " + \
            "person.Name='" + username + "';";
        db = SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_DB)
        for row in db.Execute(sql):
            if row[0] == password:
                familyID = row[1]
                session = SessionManager().CreateSession()
                SessionManager().SetProperty(EJOConst.SESSION_PROPERTY_FAMILY_ID, familyID, session)
                return True, HTTPStatus.OK, f"{{'session': '{session}'}}"

        return True, HTTPStatus.UNAUTHORIZED, "Login failed"

    def _doValidate(self):
        return True
